package com.hfzy.ihk.web.freeswitchCall.service.impl;

import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.web.freeswitchCall.context.EventSocketInitBean;
import com.hfzy.ihk.web.freeswitchCall.service.FreeswitchInfoService;
import com.hfzy.ihk.web.freeswitchCall.vo.FreeswitchChannel;
import com.hfzy.ihk.web.freeswitchCall.vo.FreeswitchGateway;
import com.hfzy.ihk.web.freeswitchCall.vo.SipRegister;
import org.freeswitch.esl.client.transport.message.EslMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * @Auther: Administrator
 * @Date: 2018/12/28 17:27
 * @Description:
 */
@Service
public class FreeswitchInfoServiceWithEslClientImpl implements FreeswitchInfoService {


    Logger logger =LoggerFactory.getLogger(FreeswitchInfoServiceWithEslClientImpl.class);

    @Autowired
    private EventSocketInitBean eventSocketInitBean;


    @Override
    public List<FreeswitchGateway> getFreeswitchGatewayList() {

        BufferedReader reader = null;
        //FileReader reader = null;
        try {
            //reader = new FileReader(new ClassPathResource("gateways.json").getFile());

            reader =new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/gateways.json"),"UTF-8"));

            char[] chars = new char[1024];

            int len;

            StringBuffer gatewayJson = new StringBuffer("");

            while ((len = reader.read(chars)) != -1) {

                gatewayJson.append(chars, 0, len);
            }

            reader.close();

            List<FreeswitchGateway> freeswitchGateways = JSON.parseArray(gatewayJson.toString(), FreeswitchGateway.class);

            return freeswitchGateways;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 返回freeswitch已经用sip注册的用户
     * @return
     */
    @Override
    public List<SipRegister> getSipRegister() {

        List<SipRegister> sipRegisters=new ArrayList<>();

        try {

            if (eventSocketInitBean.getClient()!=null&&eventSocketInitBean.getClient().canSend()){

                EslMessage message = eventSocketInitBean.getClient().sendApiCommand("sofia", "status profile internal reg");

                List<String> bodyLines = message.getBodyLines();

                for (String bodyLine : bodyLines) {

                    if (bodyLine.startsWith("Contact:")) {

                        SipRegister sipRegister=new SipRegister();

                        String user = bodyLine.substring(bodyLine.indexOf("sip:") + 4, bodyLine.indexOf("@"));

                        sipRegister.setSipUser(user);

                        String contact=bodyLine.replaceFirst("^Contact:[\\s]+","");

                        sipRegister.setContact(contact);

                        sipRegisters.add(sipRegister);
                    }

                }
            }

        }catch (Exception e){

            logger.debug("freeswitchlog: 查询sip注册用户异常");
        }

        return sipRegisters;
    }


    /**
     * 查询当前所有channls
     * @return
     */
    @Override
    public List<FreeswitchChannel> getChannels() {

        List<FreeswitchChannel>  channels=new ArrayList<>();

        try {

            if (eventSocketInitBean.getClient()!=null&&eventSocketInitBean.getClient().canSend()){

                //查询正在通话的线路
                EslMessage callMessage = eventSocketInitBean.getClient().sendApiCommand("show", "channels");

                List<String> bodyLines = callMessage.getBodyLines();

                if (bodyLines.size()>2){
                    bodyLines.remove(0);
                    bodyLines.remove(bodyLines.size()-1);
                    bodyLines.remove(bodyLines.size()-1);
                    for (String bodyLine : bodyLines) {

                        String[] split = bodyLine.split(",");

                        FreeswitchChannel  channel=new FreeswitchChannel();

                        channel.setName(split[4]);

                        channels.add(channel);
                    }
                }

            }

        }catch (Exception e){
            logger.info("freeswitchlog: 查询所有channels异常");
        }

        return channels;
    }

    ;

}
